package com.xiaozhen.mqtt.controller;

import com.xiaozhen.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dreamlu.iot.mqtt.codec.MqttMessageType;
import net.dreamlu.iot.mqtt.core.server.MqttServer;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import net.dreamlu.iot.mqtt.core.server.http.api.form.PublishForm;
import net.dreamlu.iot.mqtt.core.server.model.Message;
import net.dreamlu.iot.mqtt.core.util.PayloadEncode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.utils.hutool.StrUtil;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/11/5 11:23
 * @description:
 */
@Api(tags = "设备指令接口")
@RestController
@RequestMapping("mqtt")
public class MqttController {

    @Autowired
    private MqttServer mqttServer;

    @ApiOperation("消息发布")
    @PostMapping("/publish")
    public AjaxResult publish(@Validated @RequestBody PublishForm form) throws Exception {
        String payload = form.getPayload();
        Message message = new Message();
        message.setMessageType(MqttMessageType.PUBLISH.value());
        message.setClientId(form.getClientId());
        message.setTopic(form.getTopic());
        message.setQos(form.getQos());
        message.setRetain(form.isRetain());
        // payload 解码
        if (StrUtil.isNotBlank(payload)) {
            message.setPayload(PayloadEncode.decode(payload, form.getEncoding()));
        }
        boolean send = mqttServer.getServerCreator().getMessageDispatcher().send(form.getClientId(), message);
        if (!send) {
           return AjaxResult.error("发送失败");
        }
        return AjaxResult.success("发送成功");
    }

}
